<template>
  <div class="register">
    <el-card>
      <el-form
        :model="submitForm"
        :rules="submitRules"
        label-position="left"
        label-width="120px"
        ref="submitForm"
      >
        <el-form-item label="用户名:" prop="userName">
          <el-input placeholder="请输入用户名" v-model="submitForm.userName" />
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input placeholder="请输入密码" v-model="submitForm.password" />
        </el-form-item>
        <el-form-item label="确认密码:" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="submitForm.confirmPassword"
          />
        </el-form-item>
        <el-form-item label="昵称:" prop="nickName">
          <el-input placeholder="请输入昵称" v-model="submitForm.nickName" />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="register">注 册</el-button>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "login",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      submitForm: {
        userName: "",
        password: "",
        confirmPassword: "",
        nickName: ""
      },
      submitRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        confirmPassword: [{ validator: validatePass, trigger: "blur" }]
      }
    };
  },
  methods: {
    register() {
      this.$refs["submitForm"].validate(async valid => {
        if (valid) {
          const {
            data: { errno, message }
          } = await axios.post("/api/user/register", this.submitForm);
          if (!errno) {
            this.$message({ type: "success", message: "注册成功" });
            this.$router.push({ path: "/login" });
          } else {
            this.$message({ type: "error", message });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss">
.register {
  display: flex;
  justify-content: center;
}
</style>
